﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using TappUp_Refresh;
using TappUpsRefresh.Extras;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Devices.Sensors;
using System.Threading;
using System.Windows.Media.Imaging;
using System.IO;


namespace ImmunityBuster_wp7_2
{
    public partial class GamePage : PhoneApplicationPage
    {
        UIElementRenderer _uiRenderer;
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        
        
        
        RunningGame runGame;
        Microsoft.Devices.Sensors.Accelerometer acc = new Microsoft.Devices.Sensors.Accelerometer();
        Vector3 CalibrationVector = new Vector3();
        
        Sprite _cursor = new Sprite();
        Sprite _controller = new Sprite();
        Sprite _crossHair = new Sprite();
        private static bool loadContent { get; set; }
        Thread LoadingThread;

     
        

        public GamePage()
        {
            InitializeComponent();

           

            contentManager = (Application.Current as App).Content;
          
            (App.Current as App).currentScore.score = 0;

            LoadingThread = new Thread(() =>
                {
                    runGame = new RunningGame(contentManager);
                    runGame.LoadContent();
                    _cursor.Texture = contentManager.Load<Texture2D>("wp/cursor");
                    _controller.Texture = contentManager.Load<Texture2D>("wp/stick");
                    _controller.Bounds = new Microsoft.Xna.Framework.Rectangle(20, 400, 100, 100);
                    _crossHair.Texture = contentManager.Load<Texture2D>("crosshair");
                    _crossHair.Position = new Vector2();
                    loadContent = true;
                }
            );
            
            if (!Accelerometer.IsSupported)
                NavigationService.GoBack();

            acc.Start();
            acc.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(acc_ReadingChanged);
            acc.TimeBetweenUpdates = TimeSpan.FromTicks(666666);
            // Create a timer for this page

            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.FreeDrag | GestureType.HorizontalDrag | GestureType.Flick | GestureType.DoubleTap | GestureType.DragComplete;
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;


        }

     

      

        public void VelocityChange(Vector2 vel)
        {
            runGame.virus.Velocity = vel;
        }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {         
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            loadContent = false;

            if ((App.Current as App).currentState == States.pause)
            {
                PauseMenu.Visibility = System.Windows.Visibility.Visible;
                SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
                timer.Stop();
                return;
            }

            if (!loadContent)
                LoadingThread.Start();            

            timer.Start();

       
            
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            try
            {
                if (runGame.dSe.State == Microsoft.Xna.Framework.Audio.SoundState.Playing)
                    runGame.dSe.Pause();
            }
            catch (Exception _e)
            { }
            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            if (!loadContent)
            {
                progressBar.Value += 1;
                return;
            }
            else
            {
                if (progressBar.Value == 100)
                {
                    if (LoadingGrid.Visibility == System.Windows.Visibility.Visible)
                        LoadingGrid.Visibility = System.Windows.Visibility.Collapsed;

                    if (sp1.Visibility == System.Windows.Visibility.Collapsed)
                        sp1.Visibility = System.Windows.Visibility.Visible;
                }
            }

            if ((App.Current as App).currentState == States.playing)
            {
                (App.Current as App).currentState = runGame.Update(e, (TouchPanel.IsGestureAvailable ? TouchPanel.ReadGesture() : new GestureSample()));
                
            }

            //time.Text = (e.TotalTime.TotalMinutes.ToString() == "0" ? String.Empty : e.TotalTime.TotalMinutes.ToString()) + (int)e.TotalTime.TotalSeconds.ToString().ToCharArray().ElementAt(0) + (int)e.TotalTime.TotalSeconds.ToString().ToCharArray().ElementAt(1) + " mins";
            time.Text = (int)e.TotalTime.TotalMinutes + ":" + (int)e.TotalTime.TotalSeconds % 60 + " mins";
            score.Text = (App.Current as App).currentScore.score.ToString();
             while (TouchPanel.IsGestureAvailable)
             {
                 GestureSample gs = TouchPanel.ReadGesture();
                 _crossHair.Position = gs.Position;
                 _crossHair.Position.Y += 20;
                 _cursor.Update(e);
                 _crossHair.Update(e);

                 if ((App.Current as App).settings.ShowJoyStick)
                 {
                     Vector2 p1 = gs.Position;
                     if (_controller.Bounds.Contains((int)p1.X, (int)p1.Y))
                     {
                         Vector2 p = new Vector2();
                         p.X = _controller.CenterPosition.X - (int)gs.Position.X;
                         p.Y = _controller.CenterPosition.Y - (int)gs.Position.Y;
                         VelocityChange(p);
                     }
                 }
             }


        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            if (!loadContent)
            {
                if (_uiRenderer == null)
                    _uiRenderer = new UIElementRenderer(_mainGrid, 800, 400);
                _uiRenderer.Render();
                spriteBatch.Begin();
                spriteBatch.Draw(_uiRenderer.Texture, _uiRenderer.Texture.Bounds, Color.White);
                spriteBatch.End();
            }
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            try
            {
                _uiRenderer.Render();
                spriteBatch.Begin();
                if ((App.Current as App).currentState == States.playing)
                {
                    runGame.Draw(spriteBatch);
                    if (Power.Active)
                        spriteBatch.Draw(_crossHair.Texture, _crossHair.Position, Color.White);

                    if ((App.Current as App).settings.ShowJoyStick)
                    {
                        spriteBatch.Draw(_controller.Texture, _controller.Bounds, Color.White);
                    }
                    spriteBatch.Draw(_cursor.Texture, _cursor.Position, Color.White);
                  
                }
                else
                    if ((App.Current as App).currentState == States.Lost)
                    {
                        if (lostGame.Visibility == System.Windows.Visibility.Collapsed)
                            lostGame.Visibility = System.Windows.Visibility.Visible;
                    }
                spriteBatch.Draw(_uiRenderer.Texture, _uiRenderer.Texture.Bounds, Color.White);

                spriteBatch.End();
            }
            catch (Exception _e)
            {
                try
                {
                    spriteBatch.End();
                }
                catch (Exception __E)
                { 
                
                }
            }
        }

        private void _mainGrid_Loaded(object sender, RoutedEventArgs e)
        {
            if(_uiRenderer == null)
                _uiRenderer = new UIElementRenderer(_mainGrid, 800, 480);
        }

        private void button1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService.Navigate(new Uri("/ScorePage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {

        }

        private void quit_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.GoBack();
        }

        private void lb_Click(object sender, RoutedEventArgs e)
        {
            (App.Current as App).currentState = States.playing;
            NavigationService.Navigate(new Uri("/ScorePage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void Calibrate_Click(object sender, RoutedEventArgs e)
        {
            (App.Current as App).currentState = States.calib;
            PauseMenu.Visibility = System.Windows.Visibility.Collapsed;
            caliGrid.Visibility = System.Windows.Visibility.Visible;
        }

        private void Resume_Click(object sender, RoutedEventArgs e)
        {
            this.OnBackKeyPress(new System.ComponentModel.CancelEventArgs());
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.OnBackKeyPress(new System.ComponentModel.CancelEventArgs());
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            new Game().Exit();            
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;

            if ((App.Current as App).currentState == States.playing)
            {
                {
                    PauseMenu.Visibility = System.Windows.Visibility.Visible;
                    SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
                    timer.Stop();
                    (App.Current as App).currentState = States.pause;
                }
            }
            else
                if ((App.Current as App).currentState == States.pause)
                {
                    PauseMenu.Visibility = System.Windows.Visibility.Collapsed;
                    SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);
                    timer.Start();
                    (App.Current as App).currentState = States.playing;
                }
                else
                    if ((App.Current as App).currentState == States.calib)
                    {
                        (App.Current as App).currentState = States.pause;
                        PauseMenu.Visibility = System.Windows.Visibility.Visible;
                        caliGrid.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else
                        if ((App.Current as App).currentState == States.Lost)
                        {
                            NavigationService.GoBack();
                        }

            base.OnBackKeyPress(e);
        }

        public void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            try
            {
                if ((App.Current as App).currentState == States.calib)
                {
                    CalibrationVector = new Vector3((float)e.X, (float)e.Y, (float)e.Z);
                    return;
                }

                runGame.virus.Velocity.X = (float)e.Y + CalibrationVector.Y;
                runGame.virus.Velocity.Y = (float)e.X + CalibrationVector.X;
            }
            catch (Exception _e)
            {

            }
        }
    }
}


public enum States
{
    playing = 1,
    Lost = 2,
    Won = 3,
    calib = 4,
    pause = 5
}